//
//  WJTools.m
//  EBOexchange
//
//  Created by WWJ on 2017/12/27.
//  Copyright © 2017年 ebo. All rights reserved.
//

#import "WJTools.h"
@implementation WJTools
+ (void)drawDottedLineInView:(UIView *)view dottedLineWidth:(CGFloat)dottedLineWidth lineGap:(int)gap lineHeight:(CGFloat)lineHeight startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint lineColor:(UIColor *)lineColor{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:view.bounds];
    [shapeLayer setPosition:view.center];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
     
    // 设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:[lineColor CGColor]];
    
    // 3.0f设置虚线的高度
    [shapeLayer setLineWidth:lineHeight];
    [shapeLayer setLineJoin:kCALineJoinRound];
    
    // 3=线的宽度 1=每条线的间距
    [shapeLayer setLineDashPattern:
     [NSArray arrayWithObjects:[NSNumber numberWithInt:dottedLineWidth],
      [NSNumber numberWithInt:gap],nil]];
    
    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddLineToPoint(path, NULL, endPoint.x,endPoint.y);
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    
    [[view layer] addSublayer:shapeLayer];
}
+ (BOOL)isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES; }
    if([string isEqualToString:@"(null)"]) {return YES;}
    if ([string isKindOfClass:[NSNull class]]) { return YES; }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
        
    }
    return NO;
}
+ (NSString *)string:(double)doub fractionDigits:(int)num{
    //动态保留几位小数
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    //    formatter.groupingSize = 3;
    //设置最多保留几位小数
    formatter.maximumFractionDigits = num;
    //设置最少保留几位小数
    formatter.minimumFractionDigits = num;
    //由于最多与最少是不矛盾的所以要精确到几位小数只要同时设置就好了，如果只是最多，或只是最少的话可以把上面两行中的一行注释即可
//    formatter.groupingSeparator = @",";
    NSMutableString *str = [NSMutableString stringWithString:[formatter stringFromNumber:@(doub)]];
    
    return [str stringByReplacingOccurrencesOfString:@"," withString:@""];
}

+ (NSString *)dateFromString:(NSString *)dateSring Format:(NSString *)format{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateSring doubleValue]];
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = format?format:@"HH:mm";
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}

//二维码
+ (UIImage *)createNonInterpolatedUIImageWithDataString:(NSString *)dataString withSize:(CGFloat) size
{    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复默认
    [filter setDefaults];
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    CIImage *image = [filter outputImage];
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
    
}

+ (CGSize) boundingRectWithSize:(NSString*) txt Font:(UIFont*) font Size:(CGSize) size
{
    
    CGSize _size;
    
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
    
    NSStringDrawingUsesLineFragmentOrigin |
    
    NSStringDrawingUsesFontLeading;
    
    _size = [txt boundingRectWithSize:size options: options attributes:attribute context:nil].size;
    
#else
    
    _size = [txt sizeWithFont:font constrainedToSize:size];
    
#endif
    
    return _size;
    
}

+ (NSMutableAttributedString*)changeLabelWithText:(NSString*)needText withChangeText:(NSString *)text withFont:(UIFont *)font  color:(UIColor *)color {
    
    
    NSRange range = [needText rangeOfString:text];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:needText];
    //颜色
    [string addAttribute:NSForegroundColorAttributeName value:color range:range];
    //字体
    [string addAttribute:NSFontAttributeName value:font range:range];
    return string;
}
+ (BOOL)isEnglishWithNum:(NSString *)string {
    
    NSString *regex = @"^[A-Za-z0-9]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:string];
    return isValid;
}



+(NSMutableAttributedString*)changeLabelWithText:(NSString*)needText withChangeTextArr:(NSArray  *)textArr withFont:(UIFont *)font  color:(UIColor *)color{
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:needText];
    for (NSString *text in textArr){
        
        NSRange range = [needText rangeOfString:text];
        NSRange range1 = [needText rangeOfString:text options:NSBackwardsSearch];
        
        
        //颜色
        [string addAttribute:NSForegroundColorAttributeName value:color range:range];
        [string addAttribute:NSForegroundColorAttributeName value:color range:range1];
        
        //字体
        [string addAttribute:NSFontAttributeName value:font range:range];
        [string addAttribute:NSFontAttributeName value:font range:range1];
        
        
    }
    
    
    return string;
    
}

+ (void)addConstraintsWithView:(UIView *)view formats:(NSArray <NSString *> *)flvs views:(NSDictionary *)views{
    [self addConstraintsWithView:view metrics:nil formats:flvs views:views];
}

+ (void)addConstraintsWithView:(UIView *)view metrics:(NSDictionary *)metrics formats:(NSArray <NSString *> *)vfls views:(NSDictionary *)views{
    for (NSString *vfl in vfls) {
        NSArray *arr = [NSLayoutConstraint constraintsWithVisualFormat:vfl options:kNilOptions metrics:metrics views:views];
        [view addConstraints:arr];
    }
}

//中心对齐
+ (void)addConstraintCenterYWithView:(UIView *)view toItem:(UIView *)item1 toItem:(UIView *)item2{
    NSLayoutConstraint *con = [NSLayoutConstraint constraintWithItem:item1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:item2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [view addConstraint:con];
}

// 检测是否是手机号码
+ (BOOL)isMobileNumber:(NSString *)mobile
{
    
        if (mobile.length != 11)
            {
                    return NO;
                }
        /**
              * 手机号码:
              * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
              * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
              * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
              * 电信号段: 133,149,153,170,173,177,180,181,189
              */
        NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
        /**
              * 中国移动：China Mobile
              * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
              */
        NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
        /**
              * 中国联通：China Unicom
              * 130,131,132,145,155,156,170,171,175,176,185,186
              */
        NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
        /**
              * 中国电信：China Telecom
              * 133,149,153,170,173,177,180,181,189
              */
        NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
        
        
        NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
        NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
        NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
        NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
        
        if (([regextestmobile evaluateWithObject:mobile] == YES)
                    || ([regextestcm evaluateWithObject:mobile] == YES)
                    || ([regextestct evaluateWithObject:mobile] == YES)
                    || ([regextestcu evaluateWithObject:mobile] == YES))
            {
                    return YES;
                }
        else
            {
                    return NO;
                }
        //旧的正则表达式
    //    if (mobile.length < 11)
    //    {
    //        return NO;
    //    }else{
    //        /**
    //         * 移动号段正则表达式
    //         */
    //        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //        /**
    //         * 联通号段正则表达式
    //         */
    //        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //        /**
    //         * 电信号段正则表达式
    //         */
    //        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    //        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    //        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    //        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    //        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    //        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    //        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
    //
    //        if (isMatch1 || isMatch2 || isMatch3) {
    //            return YES;
    //        }else{
    //            return NO;
    //        }
    //    }
    //    return YES;
}


//判断是否是邮箱
+ (BOOL)validationEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if( [emailTest evaluateWithObject:email]){
        return true;
        
    }
    return false;
}
//6~20位数字、字母、下划线、减号格式校验
+ (BOOL)checkPsw:(NSString *)pswStr
{
    NSString * pattern  =   @"^[A-Za-z0-9_-]{6,20}$";
    //    NSString *condition =@"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate * pred  =   [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return [pred evaluateWithObject:pswStr];
}
//6~16位数字格式校验
+ (BOOL)checkBackPsw:(NSString *)pswStr
{
    NSString * pattern  =   @"^[0-9]{6,16}$";
    //    NSString *condition =@"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate * pred  =   [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return [pred evaluateWithObject:pswStr];
}

//检测银行卡
+ (BOOL) checkCardNo:(NSString*) cardNo{
    //是否是数字
    //    NSString * pattern  =   @"^[0-9]{6,16}$";
    //    //    NSString *condition =@"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    //    NSPredicate * pred  =   [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    //    if(![pred evaluateWithObject:cardNo]){
    //
    //    }
    if ([WJTools isBlankString:cardNo]) {
        return NO;
    }
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}

@end
